package rai;

import java.io.IOException;

import rai.model.Personne;
import rai.service.rep.Repertoire;
import rai.service.transport.RaiSocket;

public class RaiExecCommandeRep implements Runnable {
	
	protected RaiSocket socket;
	protected Repertoire rep;
	private Thread _t;
	protected boolean quitter=false;
	
	public RaiExecCommandeRep(RaiSocket socket, Repertoire rep){
		this.socket = socket;
		this.rep = rep;
		_t = new Thread(this);
		_t.start();
	}
	
	public RaiExecCommandeRep(RaiSocket socket){
		this.socket = socket;
		_t = new Thread(this);
		_t.start();
	}

	public void run() {
		try {
			while (!quitter) {

				traitement();

			}
		} catch (IOException e) {
			e.printStackTrace();
		}catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			socket.closeSocket();
		}
	}

	private void traitement() throws IOException,ClassNotFoundException {
		Commande laCommande;

		System.out.print(" Commande : ");
		laCommande = (Commande) socket.readObject();
		System.out.println(laCommande);
		executerCommande(laCommande);
	}

	protected void executerCommande(Commande laCommande) throws IOException,
			ClassNotFoundException {
		Personne p;
		String nom;
		String[] liste;
		switch (laCommande) {
		case AddPersonne:
			p = (Personne) socket.readObject();
			socket.writeBoolean(rep.ajouterPersonne(p));
			break;
		case UpgPersonne:
			p = (Personne) socket.readObject();
			socket.writeBoolean(rep.modifierPersonne(p));
			break;
		case RemPersonne:
			nom = socket.readString();
			socket.writeBoolean(rep.retirerPersonne(nom));
			break;
		case FindPersonne:
			nom = socket.readString();
			p = rep.chercherPersonne(nom);
			socket.writeObject((Object) p);
			break;
		case ListePersonnes:
			liste = rep.listerPersonnes();
			envoyerListe(liste);
			break;
		}
	}

	protected void envoyerListe(String[] liste) throws IOException {
		socket.writeInt(liste.length);
		for (String nom : liste) {
			socket.writeString(nom);
		}
	}

}
